package com.arraymasterx.service;

import com.arraymasterx.algorithm.sort.*;
import com.arraymasterx.config.AlgorithmConfig;
import com.arraymasterx.model.request.SortRequest;
import com.arraymasterx.model.response.SortResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
public class SortService {

    private final Map<String, SortAlgorithm> sortAlgorithms = new HashMap<>();
    private final AlgorithmConfig algorithmConfig;

    @Autowired
    public SortService(BubbleSort bubbleSort, QuickSort quickSort, MergeSort mergeSort, HeapSort heapSort,
            InsertionSort insertionSort, SelectionSort selectionSort, AlgorithmConfig algorithmConfig) {
        this.sortAlgorithms.put("bubble", bubbleSort);
        this.sortAlgorithms.put("quick", quickSort);
        this.sortAlgorithms.put("merge", mergeSort);
        this.sortAlgorithms.put("heap", heapSort);
        this.sortAlgorithms.put("insertion", insertionSort);
        this.sortAlgorithms.put("selection", selectionSort);
        this.algorithmConfig = algorithmConfig;
    }

    public SortResponse sort(SortRequest request, String algorithm) {
        validateInput(request.getArray());

        SortAlgorithm sorter = getSortAlgorithm(algorithm);
        int[] sortedArray = sorter.sort(request.getArray().clone());

        return new SortResponse(sortedArray, algorithm);
    }

    private SortAlgorithm getSortAlgorithm(String algorithm) {
        if (algorithm == null || algorithm.isEmpty()) {
            algorithm = algorithmConfig.getSort().getDefaultAlgorithm();
        }

        SortAlgorithm sorter = sortAlgorithms.get(algorithm.toLowerCase());
        if (sorter == null) {
            throw new IllegalArgumentException("Invalid sorting algorithm: " + algorithm);
        }
        return sorter;
    }

    private void validateInput(int[] array) {
        if (array == null) {
            throw new IllegalArgumentException("Input array cannot be null");
        }

        if (array.length > algorithmConfig.getSort().getMaxElements()) {
            throw new IllegalArgumentException(
                    "Array size exceeds maximum allowed size: " + algorithmConfig.getSort().getMaxElements());
        }
    }
}